<template>
	<fill-sentence
		v-if="visible"
		:show-timer="showTimer"
		:sentence="currentSentence"
		:word-list="currentWordList"
		:timer-bar-sty="timerBarSty"
		:jump="jump"
		@next="handleNext"
	/>
</template>

<script lang="ts" setup>
	import { ref, onMounted } from 'vue';
	import { ISentence, IWord, TestTemplates } from '@/store/study';
	import { getUuid, lodash, deepClone, randomArray } from '@/utils';
	import FillSentence from './fill-sentence.vue';
	
	/** 句子填充包装组件 */
	defineOptions({ name: 'with-fill-sentence', inheritAttrs: false, options: { virtualHost: true } })
	/** 组件属性声明 */
	const props = withDefaults(
		defineProps<{
			wordList: IWord[];
			timerBarSty?: string;
			jump?: boolean;
			showTimer?: boolean;
		}>(),
		{
			wordList: () => [],
			timerBarSty: '',
			jump: false,
			showTimer: false
		}
	)
	const emit = defineEmits(['update-group', 'next'])
	
	const visible = ref(false);
	/** 句子列表 */
	const sentenceGroup = ref<{ Key: string; WordList: IWord[]; Sentence: ISentence; FillEd: boolean }[]>([]);
	/** 需要填充的句子 */
	const currentSentence = ref<ISentence>(null)
	const currentWordList = ref<IWord[]>([]);
	// 测试基本需求：最小包含2个词汇
	const needMinWordCnt = 2;
	// 测试基本需求：最多只使用6个词汇
	const needMaxWordCnt = 6;
	
	/** 初始化数据 */
	function initData() {
		const wordList: IWord[] = deepClone(props.wordList);
		wordList.forEach(wl => {
			const SentenceEn = lodash.get(wl, 'SentenceSnapshot.SentenceEn');
			if (SentenceEn) {
				const found = sentenceGroup.value.find(sg => sg.Sentence.SentenceEn === SentenceEn)
				if (found) {
					found.WordList.push(wl)
				} else {
					sentenceGroup.value.push({
						Key: getUuid(),
						WordList: [wl],
						Sentence: wl.SentenceSnapshot,
						FillEd: false
					})
				}
			}
		})
		
		// 词汇大于2个的才可参与测试
		sentenceGroup.value.forEach(sg => {
			if (sg.WordList.length < needMinWordCnt) {
				sg.FillEd = true;
			}
		})
	}
	
	/** 填充下一个句子 */
	function nextFillTest() {
		const found = sentenceGroup.value.find(sg => !sg.FillEd)
		if (found) {
			currentSentence.value = found.Sentence;
			if (found.WordList.length > needMaxWordCnt) {
				currentWordList.value = randomArray(found.WordList).filter((_wl, index) => index < needMaxWordCnt)
			} else {
				currentWordList.value = found.WordList;
			}
			visible.value = true;
		} else {
			// 全部完成
			emit('next');
		}
	}
	
	/** 答题回调 */
	function handleNext(sentenceEn: string, isRight: boolean, answer: any[]) {
		sentenceGroup.value.forEach(sg => {
			if (sg.Sentence.SentenceEn === sentenceEn){
				sg.FillEd = true
			}
		})
		
		emit('update-group', sentenceEn, isRight, answer);
		nextFillTest();
	}
	
	initData()
	nextFillTest()
</script>

<style>
</style>